package com.cn.namesrv;

import com.cn.common.TopicRouteManager;
import com.cn.common.processor.INettyRequestProcessor;
import com.cn.common.topic.TopicManager;
import com.cn.namesrv.processor.NameSrvDefaultProcessor;
import com.cn.common.Pair;
import com.cn.common.processor.ProcessorCode;
import com.cn.exception.MyException;
import com.cn.remote.ChannelListener;
import com.cn.remote.RemoteServer;
import com.cn.util.FileConfigPropertyUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NameSrvController {

    private RemoteServer nameSrv;

    private ExecutorService defaultExecutorService;

    private FileConfigPropertyUtil config;

    private String host;

    private int port;

    private TopicManager topicManager;

    private TopicRouteManager topicRouteManager;

    private ChannelListener channelListener;

    public NameSrvController(FileConfigPropertyUtil config) {
        if (config == null) throw new MyException("配置文件异常");
        this.config = config;
        //监听地址
        this.host = config.get("namesrv_ip");
        //监听端口
        this.port = Integer.valueOf(config.get("namesrv_port"));
        String address = String.format("%s:%d", host, port);

        this.channelListener = new ChannelEventImpl(this);
        this.nameSrv = new RemoteServer(32, address);
        this.nameSrv.registerChannelListener(this.channelListener);

        defaultExecutorService = Executors.newCachedThreadPool();
        topicManager = new TopicManager(null);
        this.topicRouteManager = new TopicRouteManager();
    }

    public void start() {
        if (this.nameSrv != null) {
            this.nameSrv.start();
        }

        registerDefaultProcessor();
    }

    public void registerDefaultProcessor() {
        INettyRequestProcessor processor = new NameSrvDefaultProcessor(this);
        nameSrv.registerProcessor(ProcessorCode.pull_default, processor, this.defaultExecutorService);
    }

    public void shutDown() {
        if (this.nameSrv != null) {
            this.nameSrv.shutdown();
        }
    }

    public TopicManager getTopicManager() {
        return topicManager;
    }

    public TopicRouteManager getTopicRouteManager() {
        return topicRouteManager;
    }
}
